<?php

	defined('_JEXEC') or die('Restricted access');

	// Functions. ->
		function secondsToTime($inputSeconds) {
			$secondsInAMinute = 60;
			$secondsInAnHour  = 60 * $secondsInAMinute;
			$secondsInADay    = 24 * $secondsInAnHour;

			// extract days
			$days = floor($inputSeconds / $secondsInADay);

			// extract hours
			$hourSeconds = $inputSeconds % $secondsInADay;
			$hours = floor($hourSeconds / $secondsInAnHour);

			// extract minutes
			$minuteSeconds = $hourSeconds % $secondsInAnHour;
			$minutes = floor($minuteSeconds / $secondsInAMinute);

			// extract the remaining seconds
			$remainingSeconds = $minuteSeconds % $secondsInAMinute;
			$seconds = ceil($remainingSeconds);

			// return the final array
			$obj = array(
			    'd' => (int) $days,
			    'h' => (int) $hours,
			    'm' => (int) $minutes,
			    's' => (int) $seconds,
			);
			return $obj;
		}

	// Hent alle begivenheder der begynder fra og med i dag (dato). ->
		$db =& JFactory::getDBO();

		$query = 'SELECT * 
		FROM #__spidercalendar 
		WHERE published = 1 AND date >= CURDATE() 
		ORDER BY date ASC, time ASC';
		
		$db->setQuery($query);
		$rows = $db->loadObjectList();

	// Find den næste begivenhed (tid). ->
		$i = 0;
		foreach($rows as $begivenhed){
			$tidBegynder = explode(' - ', $begivenhed->time);
			if(strtotime($begivenhed->date.' '.$tidBegynder[0]) > time()){
				break;
			}else{
				$i++;
			}
		}

	// Omregn tid til Unix Timestamp. ->
		$time = explode(' - ', $rows[$i]->time);
		$convTime = strtotime($rows[$i]->date.' '.$time[0]);
		$untilTime = ($convTime - time());
		$return = secondsToTime($untilTime);

	// Output. ->
		echo '<b>Næste begivenhed er</b>:
		<ul>
			<li>'.$rows[$i]->title.'</li>
			<li>'.$rows[$i]->date.' ('.$rows[$i]->time.')</li>
		</ul>
		<b>Begivenhed begynder om</b>:
		<ul>';
			if(!empty($return['d'])){
				echo'<li>'.$return['d'].' dage</li>';
			}
			if(!empty($return['h'])){
				echo'<li>'.$return['h'].' timer</li>';
			}
			if(!empty($return['m'])){
				echo'<li>'.$return['m'].' minutter</li>';
			}
		echo'</ul>';

	// Debug. ->
		/*echo'<pre>';
		print_r($rows[0]);
		echo'</pre>';*/

	//-^

?>